<?php

namespace app\common\model;


use app\common\exception\ApiException;

class Order extends BaseModel {
    public function getProductsAttr($value) {
        $json = json_decode($value, true);
        return $json;
    }

    public function getCreateTimeAttr($value) {
        return date('Y-m-d H:i');
    }

    public function information() {
        return $this->hasOne('Information', 'id', 'information_id')->field('id,content,top_expert,is_top,need_pay');
    }

    public function banner() {
        return $this->hasOne('Banner', 'belong_id', 'information_id')->field('id,belong_id,cat_name,expert,title,status');
    }

    public function user() {
        return $this->hasOne('User', 'id', 'user_id')->field('id,nickName,avatarUrl');
    }

    public function getOrderList($condition) {
        if (empty($condition['status']) && !isset($condition['status'])) {
            $condition['status'] = ['neq', config('code.status_delete')];
        }
        $order  = ['id' => 'desc'];
        $result =
            $this->with(['information'])
                ->field('id,order_no,user_id,information_id,create_time,status,products,total_price')
                ->where($condition)
                ->order($order)
                ->select();
        if (!$result) {
            throw new ApiException('获取订单列表失败', 200, 1);
        }
        return $result;
    }

    public function getOrderDetail($id) {
        $result = $this->with(['information', 'banner'])
            ->where(['id' => $id])
            ->find();
        if (!$result) {
            throw new ApiException('获取订单详情失败', 200, config('code.fail'));
        }
        return $result;
    }
}